<template>
  <nut-tabbar v-model="selected" class="tabbar-container" size="18px" @tab-switch="handleClick">
    <nut-tabbar-item :tab-title="item.title" :value="item.value" v-for="(item, index) in tabList" :key="index">
      <template #icon="props" style="position: relative">
        <img v-if="props.active" :src="item.activeImg" />
        <img v-else :src="item.img" />
      </template>
    </nut-tabbar-item>
  </nut-tabbar>
</template>
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { reactive, onMounted, watch } from "vue";
import { useTabbarStore, useUserStore } from "../../store";
import Taro, { eventCenter } from "@tarojs/taro";
const tabbarStore = useTabbarStore();
const userStore = useUserStore();
const { selected, bottomDistance } = storeToRefs(tabbarStore);
const router = Taro.useRouter();

type menu = {
  name: string;
  title: string;
  pagePath: string;
  img: any;
  activeImg: any;
  value: number;
};
watch(selected, (newValue) => {
  // Taro.setStorageSync("selectedTab", newValue);
  tabbarStore.setSelected(newValue);
});
onMounted(() => {
  tabbarStore.setSelected(Taro.getStorageSync("selectedTab") || 0);
  eventCenter.once(router.onReady, () => {
    getTabbarHeight();
  });
});

//计算tabbarBar的高度
const getTabbarHeight = () => {
  const query = Taro.createSelectorQuery()
    .select(".tabbar-container")
    .boundingClientRect();
  query.selectViewport();
  query.exec(function (res) {
    if (res[0]) {
      console.log(res);

      const height = res[0].height;
      tabbarStore.setTabbarHeight(height);
    }
  });
};
const tabList = reactive<menu[]>([
  {
    name: "home",
    title: "电影票",
    pagePath: "/pages/index/index",
    img: require("../../assets/tabbar/1/movie.png"),
    activeImg: require("../../assets/tabbar/2/movie.png"),
    value: 0,
  },
  {
    name: "goods",
    title: "选好货",
    pagePath: "/pages/goods/index",
    img: require("../../assets/tabbar/1/goods.png"),
    activeImg: require("../../assets/tabbar/2/goods.png"),
    value: 0,
  },

  {
    name: "action",
    title: "订单",
    pagePath: "/pages/order/index",
    img: require("../../assets/tabbar/1/order.png"),
    activeImg: require("../../assets/tabbar/2/order.png"),
    value: 0,
  },
  {
    name: "report",
    title: "我的",
    pagePath: "/pages/my/index",
    img: require("../../assets/tabbar/1/my.png"),
    activeImg: require("../../assets/tabbar/2/my.png"),
    value: 0,
  },
]);
const handleClick = (item, index: number) => {
  let url = tabList[index].pagePath;

  const pages = Taro.getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (currentPage.route !== url) {
    handleToPath(url);
  }
};
const handleToPath = (url) => {
  Taro.switchTab({
    url: url,
  });
};
</script>
<style lang="scss">
@import "./customTabBar.scss";
</style>
